package com.fingard.dsp.bank.directbank.citic01;

import com.fingard.dsp.bank.directbank.bankInterface.IBalance;
import com.fingard.dsp.bank.reqrespobj.balance.Req7505HisBalQry;
import com.fingard.dsp.bank.reqrespobj.balance.Req7506BalQry;
import com.fingard.dsp.bank.reqrespobj.balance.RetAts7505HisBalQry;
import com.fingard.dsp.bank.reqrespobj.balance.RetAts7506BalQry;
import com.fingard.dsp.bank.reqrespobj.balance.detail.RetAtsBalDetail;
import com.fingard.dsp.bank.reqrespobj.balance.detail.RetAtsHisBalDetail;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

public class CITIC01Balance extends CITIC01Base implements IBalance {

	//单个余额查询和批量余额查询，统一采用流处理方式
	//1、循环调用Req7506BalQry.readRecord()读取一个请求明细，然后写入发银行的XML对象
	//2、发银行
	//3、循环调用XmlTextReader.read()读取一个银行返回节点，赋值返回ATS的明细对象，
	//   然后调用RetAts7506BalQry.writeRetDetail()，写入返回ATS的明细
	public RetAts7506BalQry d_7506_BalQry(Req7506BalQry p_req7506) throws Exception {

		if (p_req7506.isSameActBankType()) {
			boolean hasSubAct = false;
			boolean hasOtherAct = false;
			while(p_req7506.readRecord()) {
				if("2".equals(p_req7506.readedDetail.actBankType) && StringHelper.hasAnyChar(p_req7506.readedDetail.higherLevelAct)) {
					hasSubAct = true;
				} else {
					hasOtherAct = true;
				}
			}
			p_req7506.backToTop();
			if(hasSubAct && hasOtherAct) {
				throw new Exception("暂不支持多种账户类型进行批量查询！");
			} else if(hasSubAct) {
				return d_7506_SubBalQry(p_req7506);//3.5.6 附属账户余额查询
			}
			return d_7506_BalQry_TotalAct(p_req7506);
		} else {
			throw new Exception("暂不支持多种账户类型进行批量查询！");
		}

	}

	//3.5.6 附属账户余额查询
	private RetAts7506BalQry d_7506_SubBalQry(Req7506BalQry p_req7506) throws Exception {
		//余额查询返回ATS的对象
		RetAts7506BalQry retAts = new RetAts7506BalQry(p_req7506.reqHeader);
		retAts.writeStart();//写返回ATS的统一头部信息
		try {
			CITIC01Header bankHeader = new CITIC01Header();
			bankHeader.action = "DLSUBBAL";
			XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
			//写入通用的头部节点
			writeCommonHeader(xmlWriter, bankHeader);
			while (p_req7506.readRecord()) {
				xmlWriter.writeElementString("subAccNo", p_req7506.readedDetail.actNum);
			}
			xmlWriter.writeEndDocument();
			String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
			if (tmpStrRet[0].length() == 0) {
				StringBuilder tmpSbMsg = new StringBuilder();
				XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
				if (tmpBkReader != null) {
					String tmpStatus = tmpBkReader.getFirstText("/stream/status");
					String tmpStatusText = tmpBkReader.getFirstText("/stream/statusText");
					if (tmpStatus != null && "AAAAAAA".equals(tmpStatus)) {
						while (tmpBkReader.read("/stream/list/row")) {
							RetAtsBalDetail tmpRetDetail = new RetAtsBalDetail();
							if ("AAAAAAA".equals(tmpBkReader.readedXElement.getSingleText("status"))) {
								tmpRetDetail.respCode = "0";
								tmpRetDetail.respInfo = tmpBkReader.readedXElement.getSingleText("statusText");
								tmpRetDetail.actCur = convertCurToATS(tmpBkReader.readedXElement.getSingleTextNotNull("cryType"));
								tmpRetDetail.actNum = tmpBkReader.readedXElement.getSingleText("subAccNo");
								tmpRetDetail.currBal = tmpBkReader.readedXElement.getSingleText("balance");
								tmpRetDetail.availBal = tmpBkReader.readedXElement.getSingleText("actBal");
								tmpRetDetail.frozenBal = tmpBkReader.readedXElement.getSingleText("frozenAmt");
							} else {
								tmpRetDetail.respCode = "-1";
								tmpRetDetail.respInfo = tmpBkReader.readedXElement.getSingleText("status") + "-" + tmpBkReader.readedXElement.getSingleText("statusText");
							}
							retAts.writeRetDetail(tmpRetDetail, p_req7506.isBatch);
						}
					} else {
						retAts.writeBatRespCode("-1");
						retAts.writeRespInfo(tmpStatusText);
					}
				}
			} else {
				retAts.writeRespCode("-1");
				retAts.writeRespInfo(tmpStrRet[1]);
			}
		} catch (Exception e) {
			retAts.writeRespCode("-1");
			retAts.writeRespInfo(e.getMessage());
			e.printStackTrace();
		}
		retAts.writeEnd();
		return retAts;
	}


	public RetAts7506BalQry d_7506_BalQry_TotalAct(Req7506BalQry p_req7506) throws Exception{//余额查询
		//余额查询返回ATS的对象
		RetAts7506BalQry retAts = new RetAts7506BalQry(p_req7506.reqHeader);
		retAts.writeStart();//写返回ATS的统一头部信息
		boolean isVirtualAccount=false;
		try {
			//赋值通用参数
			CITIC01Header bankHeader = new CITIC01Header();
			bankHeader.action = "DLBALQRY";

			XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
			//写入通用的头部节点
			writeCommonHeader(xmlWriter, bankHeader);
			//xmlWriter.writeElementString("TotalNum", String.valueOf(p_req7506.detailCount));
			/*
<list name="userDataList">
<row>
<accountNo></accountNo><!--账号char(19)-->
		</row>

			 * */
				xmlWriter.writeStartElementByAttr("list", "<list name=\"userDataList\">");
				while (p_req7506.readRecord()) {
					if(p_req7506.readedDetail.higherLevelAct!=null&&p_req7506.readedDetail.higherLevelAct.length()>0) {
						isVirtualAccount = true;
						bankHeader.action = "DLSBALQR";
						XmlTextWriter tmpXmlWriter = new XmlTextWriter();//发银行报文的XML对象
						writeCommonHeader(tmpXmlWriter, bankHeader);
						tmpXmlWriter.writeElementString("accountNo", p_req7506.readedDetail.higherLevelAct);
						tmpXmlWriter.writeElementString("subAccNo", p_req7506.readedDetail.actNum);
						xmlWriter=tmpXmlWriter;
					}else {
						xmlWriter.writeStartElement("row");
						xmlWriter.writeElementString("accountNo", p_req7506.readedDetail.actNum);
						xmlWriter.writeEndElement();
					}
				}

			xmlWriter.writeEndDocument();
			
			String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
			if(tmpStrRet[0].length() == 0){
				StringBuilder tmpSbMsg = new StringBuilder();
				
				XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
				
				if(tmpBkReader != null){
					String tmpStatus = tmpBkReader.getFirstText("/stream/status");
					String tmpStatusText = tmpBkReader.getFirstText("/stream/statusText");
					if(tmpStatus != null && tmpStatus.equals("AAAAAAA")) {
						while (tmpBkReader.read("/stream/list/row")) {
							RetAtsBalDetail tmpRetDetail = new RetAtsBalDetail();
							//tmpRetDetail.actCur = convertCurToATS(tmpBkReader.readedXElement.getSingleText("CurrType"));
							if (isVirtualAccount == false) {
								tmpRetDetail.actNum = tmpBkReader.readedXElement.getSingleText("accountNo");
							} else {
								tmpRetDetail.actNum = tmpBkReader.readedXElement.getSingleText("subAccNo");
							}
							if (isVirtualAccount == false) {
								if (tmpBkReader.readedXElement.getSingleText("status").equals("AAAAAAA")) {
									tmpRetDetail.respCode = "0";
									tmpRetDetail.availBal = tmpBkReader.readedXElement.getSingleText("usableBalance");
									tmpRetDetail.currBal = tmpBkReader.readedXElement.getSingleText("balance");
									tmpRetDetail.frozenBal = tmpBkReader.readedXElement.getSingleText("forzenAmt");
									//currencyID币种
									String tmpLastTranDate = tmpBkReader.readedXElement.getSingleText("lastTranDate");
									if (!StringHelper.isNullOrEmpty(tmpLastTranDate) && tmpLastTranDate.length() == 8) {
										tmpRetDetail.lastTranDate = tmpLastTranDate.substring(0, 4) + "-" + tmpLastTranDate.substring(4, 6) + "-" + tmpLastTranDate.substring(6, 8);
									}
								} else {
									tmpRetDetail.respCode = "-1";
									tmpRetDetail.respInfo = tmpBkReader.readedXElement.getSingleText("status") + "-" + tmpBkReader.readedXElement.getSingleText("statusText");
								}
								retAts.writeRetDetail(tmpRetDetail, p_req7506.isBatch);
							} else {
								tmpRetDetail.respCode = "0";
								tmpRetDetail.availBal = tmpBkReader.readedXElement.getSingleText("SJAMT");
								tmpRetDetail.currBal = tmpBkReader.readedXElement.getSingleText("SJAMT");
								tmpRetDetail.frozenBal = tmpBkReader.readedXElement.getSingleText("DJAMT");
								retAts.writeRetDetail(tmpRetDetail, p_req7506.isBatch);
							}
						}
					}
					else{
						retAts.writeRespCode("-1");
						retAts.writeRespInfo(tmpStatusText);
					}
				}
				else{
					retAts.writeRespCode("-1");
					retAts.writeRespInfo(tmpSbMsg.toString());
				}
			}
			else{
				retAts.writeRespCode("-1");
				retAts.writeRespInfo(tmpStrRet[1]);
			}
		} catch (Exception e) {
			retAts.writeRespCode("-1");
			retAts.writeRespInfo(e.getMessage());
			e.printStackTrace();
		}
		retAts.writeEnd();
		return retAts;
	}

	@Override
	public RetAts7505HisBalQry d_7505_BalQry(Req7505HisBalQry p_req7505) throws Exception {
        RetAts7505HisBalQry retAts = new RetAts7505HisBalQry(p_req7505.reqHeader);
        String tmpRespCode = "";
        String tmpRespInfo = "";
        retAts.writeStart();//写返回ATS的统一头部信息
        try {
            CITIC01Header bankHeader = new CITIC01Header();
            bankHeader.action = "DLHBLQRY";
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            //写入通用的头部节点
            writeCommonHeader(xmlWriter, bankHeader);
            xmlWriter.writeElementString("accountNo", p_req7505.actNum);
            xmlWriter.writeElementString("startDate", p_req7505.dateFrom);
            xmlWriter.writeElementString("endDate", p_req7505.dateTo);
            xmlWriter.writeEndDocument();

            String[] tmpRetBkStr = sendToBank(xmlWriter.toXmlString());

            XmlTextReader tmpBkReader;
            if (tmpRetBkStr[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                tmpBkReader = loadBankRespXmlReader(tmpRetBkStr[1], tmpSbMsg);
                if(tmpBkReader != null){
                    String tmpStatus = tmpBkReader.getFirstText("/stream/status");
                    String tmpStatusText = tmpBkReader.getFirstText("/stream/statusText");
                    if (isActiveRetCode(tmpStatus)){
                        while (tmpBkReader.read("/stream/list/row")) {
                            RetAtsHisBalDetail tmpRetDetail = new RetAtsHisBalDetail();
                            String tmpETYDAT = tmpBkReader.readedXElement.getSingleText("date");
                            if (tmpETYDAT.length() == 8) {
                                tmpRetDetail.balDate = tmpETYDAT.substring(0, 4) + "-" + tmpETYDAT.substring(4, 6) + "-" + tmpETYDAT.substring(6, 8);
                            } else {
                                tmpRetDetail.balDate = tmpETYDAT;
                            }
                            tmpRetDetail.actBal = tmpBkReader.readedXElement.getSingleText("balance");
                            retAts.writeRetDetail(tmpRetDetail);
                        }
                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpStatusText;
                    }
                } else {
                    tmpRespCode = "-1";
                    tmpRespInfo = tmpSbMsg.toString();
                }
            } else {
                tmpRespCode = "-1";
                tmpRespInfo = tmpRetBkStr[1];
            }

        } catch (Exception e) {
            tmpRespCode = "-1";
            tmpRespInfo = e.getMessage();
            e.printStackTrace();
        }
        if (tmpRespCode.equals("-1")) {
            retAts = new RetAts7505HisBalQry(p_req7505.reqHeader);
            retAts.writeStart();//写返回ATS的统一头部信息
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("返回结果为空，所查询时间段内不存在历史余额");
        }
        retAts.writeEnd();
        return retAts;
	}

}
